import { Row, Col,Button, Modal, message } from 'antd';
import { WeaBrowser, WeaNewScroll, WeaRichText } from 'ecCom';
import { inject, observer } from 'mobx-react';
import { imgZoom} from '../../util/index';
const confirm = Modal.confirm;
import {toJS} from 'mobx';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

@observer
class TabDiscuss extends React.Component {
	constructor(props) {
		super(props);
	}
	
	

	componentDidMount() {
		let dom = ReactDOM.findDOMNode(this);
		imgZoom(dom, ".wea-cl-content");
	}
	componentWillReceiveProps(nextProps) {
   
	}
	componentDidUpdate(prevProps, prevState) {
		let dom = ReactDOM.findDOMNode(this);
		imgZoom(dom, ".wea-cl-content");
	}

	componentWillUnmount(){
		const {setBrowserList} = this.props.contentStore;
		setBrowserList({
			'create': {remark: ''},
			datas: [],
		})
    }

	render() {
		const {exchangeList,_BrowserList} = this.props.contentStore;
		let _exchangeList = toJS(exchangeList);
		let BrowserList = toJS(_BrowserList);
		const { sortid } = this.props;
		let exchangeListDatas = _exchangeList ? _exchangeList.datas : [];
		let wf_auth_url = _exchangeList ? _exchangeList.wf_auth_url : "";
		let doc_auth_url = _exchangeList ? _exchangeList.doc_auth_url : "";
		let acc_auth_url = _exchangeList ? _exchangeList.acc_auth_url : "";

		let bottomBarConfig = [];
		let mirror = {
			Document: { type: 37, name: getLabel(126529,"文档"), icon: 'icon-blog-Document' },
			Flow: { type: 152, name: getLabel(131692,"流程"), icon: 'icon-blog-Process' },
			Customer: { type: 18, name: getLabel(30043,"客户"), icon: 'icon-blog-Personnel' },
			Project: { type: 135, name: getLabel(30046,"项目"), icon: 'icon-blog-Project' },
			Task: { type: 'prjtsk', name: getLabel(383349,"任务"), icon: 'icon-blog-Task' },
		}
		let objDocument = {
			name: 'Browser',
			show: <div className="wea-cb-item">
				<span className={`wea-cbi-icon ${mirror['Document'].icon}`} />
				<span className="wea-cbi-text">{mirror['Document'].name}</span>
			</div>,
			type: mirror['Document'].type,
			title: mirror['Document'].name,
		};
		let objFlow = {
			name: 'Browser',
			show: <div className="wea-cb-item">
				<span className={`wea-cbi-icon ${mirror['Flow'].icon}`} />
				<span className="wea-cbi-text">{mirror['Flow'].name}</span>
			</div>,
			type: mirror['Flow'].type,
			title: mirror['Flow'].name,
		};
		let objCustomer = {
			name: 'Browser',
			show: <div className="wea-cb-item">
				<span className={`wea-cbi-icon ${mirror['Customer'].icon}`} />
				<span className="wea-cbi-text">{mirror['Customer'].name}</span>
			</div>,
			type: mirror['Customer'].type,
			title: mirror['Customer'].name,
		};

		let objProject = {
			name: 'Browser',
			show: <div className="wea-cb-item">
				<span className={`wea-cbi-icon ${mirror['Project'].icon}`} />
				<span className="wea-cbi-text">{mirror['Project'].name}</span>
			</div>,
			type: mirror['Project'].type,
			title: mirror['Project'].name,
		};
		let objTask = {
			name: 'Browser',
			show: <div className="wea-cb-item">
				<span className={`wea-cbi-icon ${mirror['Task'].icon}`} />
				<span className="wea-cbi-text">{mirror['Task'].name}</span>
			</div>,
			type: mirror['Task'].type,
			title: mirror['Task'].name,
		};

		_exchangeList.docids && bottomBarConfig.push(objDocument);//相关文档
		_exchangeList.relatedwf && bottomBarConfig.push(objFlow);//相关流程
		_exchangeList.relatedcus && bottomBarConfig.push(objCustomer);//相关客户
		_exchangeList.projectids && bottomBarConfig.push(objProject);//相关项目
		_exchangeList.relatedprj && bottomBarConfig.push(objTask);//相关任务
		_exchangeList.relateddoc && bottomBarConfig.push({
			name: 'Upload',
			show: <div className="wea-cb-item">
				<span className='wea-cbi-icon icon-blog-Enclosure' />
				<span className="wea-cbi-text">{getLabel(128158,"附件")}</span>
			</div>,
			uploadId: 'project_edit',
			uploadUrl: `${_exchangeList.relateddoc.uploadUrl}?category=${_exchangeList.relateddoc.category}`,
			category: _exchangeList.relateddoc.category,
			maxUploadSize: _exchangeList.relateddoc.maxSize,
			style: { display: "inline-block", padding: 0 }
		})
		//相关附件--relateddoc
		let browserParam = {
			hasAddBtn: false,
			hasAdvanceSerach: true,
			idSeparator: ",",
			isAutoComplete: 1,
			isDetail: 0,
			isMultCheckbox: false,
			isSingle: true,
			linkUrl: "/hrm/resource/HrmResource.jsp?id=",
			pageSize: 10,
			quickSearchName: "",
			title: getLabel(383424,"人力资源"),
			type: "1",
			viewAttr: 1,
		}
		return (
			<div className="wea-prj-tabDiscuss"
				style={{ backgroundColor: '#f7f7f7', padding: '16px 16px 0 16px', height: '100%' }}
			>
				{
					Array.isArray(BrowserList.datas) && BrowserList.datas.map((element, index) => {
						let replaceDatas = [];
						replaceDatas.push(element.creater);
						let baseParams = {
							'37': 'docids',
							'152': 'relatedwf',
							'18': 'relatedcus',
							'135': 'projectids',
							'prjtsk': 'relatedprj',
						}
						element['id'] == BrowserList[element['id']]
						let newbottomBarConfig = bottomBarConfig.map((_element, _index) => {
							_element['memorise'] = true
							for (let key in BrowserList) {
								if (key == element['id']) {
									return { ..._element, replaceDatas: BrowserList[element['id']][baseParams[_element.type]] }
								}
							}
							return _element
						})
						let bottomBarRight={	
							Component: <span style={{position:'absolute',right:'10px'}}>
								<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8yp32z@submit`} key="submit" type="primary" style={{ display: 'inline-block', borderRadius: '3px' }} onClick={() => this.dosubmit(element.id)} ><span className="icon-coms-Release" style={{ paddingRight: '7px' }} />{getLabel(383336,"提交")}</Button>
								<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4n1iwe@cancel`} key="cancel" type="primary" style={{ display: element.id != 'create' ? 'inline-block' : 'none', marginLeft: '5px', borderRadius: '3px' }} onClick={() => { this.docancel(index) }} >{getLabel(31129,"取消")}</Button>
							</span>
						};


						let show = element.isEdit == true ?
							<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@h9mkdb`} height='252px'>
								<div style={{ backgroundColor: '#ffffff', height: '242px', marginBottom: '10px' }}>
									<WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@79055b`}
										id={`${element.id}_discuss`}
										ref={`${element.id}_discuss`}
										value={BrowserList[element.id].remark}
										ckConfig={{
											toolbar: [
												{ name: 'document', items: ['Source'] },
												{ name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList'] },
												{ name: 'styles', items: ['Format', 'Font', 'FontSize'] },
												{ name: 'colors', items: ['TextColor'] },
												{ name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike',] },
												{ name: 'insert', items: ['Image', 'Table', 'Smiley'] }
											],
											extraPlugins: 'autogrow',
											height: 150,
											autoGrow_minHeight: 150,
											autoGrow_maxHeight: 160,
											removePlugins: 'resize',
											uploadUrl: '/api/doc/upload/uploadFile?model=reply',
										}}
										bottomBarConfig={newbottomBarConfig}
										bottomBarRight={bottomBarRight}
										onChange={(text) => this.onChange(element.id, text)}
										onStatusChange={s => { }}
										onToolsChange={(name, ids, list, type) => this.transfStr(name, ids, list, type, element.id)}
									/>
								</div>
							</WeaNewScroll>
							: <div style={{ borderBottom: '1px solid #E2E2E2', padding: "10px 10px 0 10px", backgroundColor: '#ffffff' }}>
								<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@kx952b`} >
									<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@2kot4f@${index}`} span={2}>
										<img src={`${element.creater.imgurl}`} style={{ height: '40px', width: '40px', borderRadius: '20px' }} />
									</Col>
									<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@sorqsm@${index}`} span={22}>

										<div style={{ marginBottom: '8px' }}>
											<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@r90h66@${index}`} {...browserParam} replaceDatas={replaceDatas} />
										</div>

										<div
											className="wea-cl-content"
											dangerouslySetInnerHTML={{__html: `<div class="wea-ckeditor-content">${element.remark}</div>`}}
										/>
										{
											element.projectids.length > 0 ?
												element.projectids.map((e, _index) => {//相关项目
													return <div>
														<span className="icon-blog-Project" style={{ paddingRight: '5px' }} />
														<a href='javascript:void(0)' linkid={e.id} linkType='workflow'
															onClick={() => openProjectAppLink('project', e.id, sortid)} ondblclick={() => false}
															unselectable='off' contenteditable='false' style={{ cursor: 'pointer', textDecoration: 'underline !important', marginRight: '8px' }}>{e.name} </a>
													</div>
												}) : ''
										}
										{
											element.relatedcus.length > 0 ?
												element.relatedcus.map((e, _index) => {//客户
													return <div>
														<span className="icon-blog-Personnel" style={{ paddingRight: '5px' }} />
														<a href='javascript:void(0)' linkid={e.id} linkType='workflow'
															onClick={() => openProjectAppLink('crm', e.id, sortid)} ondblclick={() => false}
															unselectable='off' contenteditable='false' style={{ cursor: 'pointer', textDecoration: 'underline !important', marginRight: '8px' }}>{e.name} </a>
													</div>
												}) : ''
										}
										{
											element.relateddoc.length > 0 ?
												element.relateddoc.map((e, _index) => {//修改成附件
													if (e.showLoad) {
														return <div>
															<span className="icon-blog-Enclosure" style={{ paddingRight: '5px' }} />
															<a onClick={() => openProjectDiscussDoc(this, e.fileid, sortid,acc_auth_url)} href='javascript:void(0);'
																unselectable='off' contenteditable='false' style={{ cursor: 'pointer', textDecoration: 'underline !important', marginRight: '8px' }}>{e.filename}</a>
															<a unselectable='off' contenteditable='false' href={e.loadlink+acc_auth_url} target='_blank'
																 style={{ cursor: 'pointer', textDecoration: 'underline !important', marginRight: '8px' }}>{`${getLabel(258,"下载")}(${e.filesize})`}</a>
														</div>
													} else {
														return <div>
															<span className="icon-blog-Enclosure" style={{ paddingRight: '5px' }} />
															<a onClick={() => openProjectDiscussDoc(this, e.fileid, sortid,acc_auth_url)} href='javascript:void(0);'
																unselectable='off' contenteditable='false' style={{ cursor: 'pointer', textDecoration: 'underline !important', marginRight: '8px' }}>{e.filename}</a>
														</div>
													}
												}) : ''
										}
										{
											element.relatedprj.length > 0 ?
												element.relatedprj.map((e, _index) => {
													return <div>
														<span className="icon-blog-Task" style={{ paddingRight: '5px' }} />
														<a href='javascript:void(0)' linkid={e.id} linkType='workflow'
															onClick={() => openProjectAppLink('task', e.id, sortid)} ondblclick={() => false}
															unselectable='off' contenteditable='false' style={{ cursor: 'pointer', textDecoration: 'underline !important', marginRight: '8px' }}>{e.name} </a>
													</div>
												}) : ''
										}
										{
											element.relatedwf.length > 0 ?
												element.relatedwf.map((e, _index) => {//流程
													return <div>
														<span className="icon-blog-Process" style={{ paddingRight: '5px' }} />
														<a href='javascript:void(0)' linkid={e.id} linkType='workflow'
															onClick={() => openProjectAppLink('workflow', e.id, sortid,wf_auth_url)} ondblclick={() => false}
															unselectable='off' contenteditable='false' style={{ cursor: 'pointer', textDecoration: 'underline !important', marginRight: '8px' }}>{e.name} </a>
													</div>
												}) : ''
										}
										{
											element.docids.length > 0 ?
												element.docids.map((e, _index) => {//文档
													return <div>
														<span className="icon-blog-Document" style={{ paddingRight: '5px' }} />
														<a href='javascript:void(0)' linkid={e.id} linkType='workflow'
															onClick={() => openProjectAppLink('doc', e.id, sortid,doc_auth_url)} ondblclick={() => false}
															unselectable='off' contenteditable='false' style={{ cursor: 'pointer', textDecoration: 'underline !important', marginRight: '8px' }}>{e.name} </a>
													</div>
												}) : ''
										}
									</Col>
									{/*</WeaNewScroll>*/}
								</Row>
								<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@clbkgd@${index}`} style={{ margin: '10px 0' }}>
									<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@emr6hm@${index}`} span={8} offset={2}>
										<span style={{ color: '#999999' }}>
											{element.time}
										</span>
									</Col>
									<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@oxjn3c@${index}`} span={14}>
										{
											element.canedit ? (
												<span
													className="wea-mbwcbr-item icon-coms-edit"
													style = {{cursor:'pointer',position:'absolute',right:'90px',color: '#b2b2b2'}}
													onClick={() => this.edit(element.id)}
												><span style={{ fontSize: "12px", color: '#666666' }}>&nbsp;{`${getLabel(126036,"编辑")}`}</span></span>
											) : ""
										}
										{
											element.canedit ? (
												<span
													className="wea-mbwcbr-item icon-coms-delete"
													onClick={() => this.delete(element.id)}
													style = {{position:'absolute',right:'20px',cursor:'pointer', color: '#b2b2b2'}}
												><span style={{ fontSize: "12px", color: '#666666' }}>&nbsp;{`${getLabel(131966,"删除")}`}</span></span>
											) : ""
										}
									</Col>
								</Row>

							</div>
						return show
					})
				}
				{
					exchangeListDatas.length == 1 ?
						<div style={{ textAlign: 'center', height: '135px' }}>
							<span className="icon-blog-Unhappy" style={{ display: 'inline-block', marginTop: '50px' }}><span style={{ paddingLeft: '5px' }}>{getLabel(383567,"暂无相关交流")}</span></span>
						</div>
						: ''
				}
			</div>
		)
	}


	edit = (_id) => {
		const {exchangeList,changeDiscussList,_BrowserList,setBrowserList} = this.props.contentStore;
		let _exchangeList = toJS(exchangeList);
		let BrowserList = toJS(_BrowserList);
		let oldBrowserList = { ...BrowserList };
		let oldexchangeList = { ..._exchangeList }
		oldexchangeList.datas.forEach((element, index) => {
			if (_id == element['id']) {
				element.isEdit = true;
				if (oldBrowserList[_id] == undefined) {
					oldBrowserList[_id] = {};
				}
				oldBrowserList[_id].relatedwf = element.relatedwf;
				oldBrowserList[_id].docids = element.docids;
				oldBrowserList[_id].projectids = element.projectids;
				oldBrowserList[_id].relatedcus = element.relatedcus;
				oldBrowserList[_id].relateddoc = element.relateddoc;
				oldBrowserList[_id].relatedprj = element.relatedprj;
			}
		})
		setBrowserList(oldBrowserList);
		changeDiscussList(oldexchangeList)
	}
	onChange = (id, text) => {
		const {_BrowserList,setBrowserList} = this.props.contentStore;
		let BrowserList = toJS(_BrowserList);
		let oldBrowserList = { ...BrowserList };
		if (oldBrowserList[id] == undefined) {
			oldBrowserList[id] = {};
		}
		oldBrowserList[id]['remark'] = text;
		setBrowserList(oldBrowserList);
	}
	delete = (e) => {
		const {exchangeDelete} = this.props.contentStore;
		const { sortid } = this.props;
		confirm({
			title : getLabel(131329,"信息确认"),
			content : getLabel(15097,"确定要删除吗？"),
			onOk(){
				exchangeDelete({ id: e, sortid: sortid });
			},
			onCancel() {}
	})

	}
	dosubmit = (id) => {
		const {exchangeSave,_BrowserList,setBrowserList} = this.props.contentStore;
		let BrowserList = toJS(_BrowserList);
		let oldBrowserList = { ...BrowserList }
		const { sortid } = this.props;
		let params = oldBrowserList[id];
		let mewParams = { ...params }
		let canSubmit = false;
		for (let key in mewParams) {
			if (key != 'id' && key != 'sortid') {
				if (key == 'remark') {
					if (mewParams[key]) {
						canSubmit = true
					}
				}
			}
		}

		if (params.docids.length == 0) {
			delete mewParams.docids
		}
		if (params.projectids.length == 0) {
			delete mewParams.projectids
		}
		if (params.relatedcus.length == 0) {
			delete mewParams.relatedcus
		}
		if (params.relateddoc.length == 0) {
			delete mewParams.relateddoc
		}
		if (params.relatedprj.length == 0) {
			delete mewParams.relatedprj
		}
		if (params.relatedwf.length == 0) {
			delete mewParams.relatedwf
		}
		if (params.docids.length > 0) {
			let docidsarr = []
			params.docids.forEach((_e, _index) => {
				docidsarr.push(_e['id']);
			})
			mewParams.docids = docidsarr.join(',');
		}
		if (params.projectids.length > 0) {
			let projectidssarr = []
			params.projectids.forEach((_e, _index) => {
				projectidssarr.push(_e['id']);
			})
			mewParams.projectids = projectidssarr.join(',');

		}
		if (params.relatedcus.length > 0) {//客户和任务有问题
			let relatedcusarr = []
			params.relatedcus.forEach((_e, _index) => {
				relatedcusarr.push(_e['id']);
			})
			mewParams.relatedcus = relatedcusarr.join(',');

		}
		if (params.relateddoc.length > 0) {
			let relateddocarr = []
			params.relateddoc.forEach((_e, _index) => {
				relateddocarr.push(_e['id']);
			})
			mewParams.relateddoc = relateddocarr.join(',');

		}
		if (params.relatedprj.length > 0) {
			let relatedprjarr = []
			params.relatedprj.forEach((_e, _index) => {
				relatedprjarr.push(_e['id']);
			})
			mewParams.relatedprj = relatedprjarr.join(',');

		}
		if (params.relatedwf.length > 0) {
			let relatedwfarr = []
			params.relatedwf.forEach((_e, _index) => {
				relatedwfarr.push(_e['id']);
			})
			mewParams.relatedwf = relatedwfarr.join(',');

		}
		mewParams['id'] = id == 'create' ? '' : id;
		mewParams['sortid'] = sortid;
		let stateBrowserList = { ...BrowserList };
		stateBrowserList['create']['docids'] = []
		stateBrowserList['create']['projectids'] = []
		stateBrowserList['create']['relatedcus'] = []
		stateBrowserList['create']['relateddoc'] = []
		stateBrowserList['create']['relatedprj'] = []
		stateBrowserList['create']['relatedwf'] = []
		stateBrowserList['create']['remark'] = ''

		if (canSubmit) {
			setBrowserList(stateBrowserList);
			exchangeSave(mewParams);
		} else {
			message.error(getLabel(126982,"请填写内容"));
			// Modal.warning({
			// 	title: getLabel(382056,"警告"),
			// 	content: getLabel(126982,"请填写内容"),
			// });
		}
	}

	docancel = (e) => {
		const {exchangeList,changeDiscussList} = this.props.contentStore;
		let _exchangeList = toJS(exchangeList);
		let oldexchangeList = { ..._exchangeList }
		oldexchangeList.datas.forEach((element, index) => {
			if (e == index) {
				element.isEdit = false;
			}
		})
		changeDiscussList(oldexchangeList)
	}

	transfStr = (name = '', ids = '', list = [], type = '', id = '') => {
		const {_BrowserList,setBrowserList,exchangeList} = this.props.contentStore;
		let BrowserList = toJS(_BrowserList);
		let _exchangeList = toJS(exchangeList);
		let acc_auth_url = _exchangeList ? _exchangeList.acc_auth_url : "";
		let { sortid } = this.props;
		let str = '';
		let idsArr = [];
		const mirror = {
			37: "doc",
			prjtsk: "task",
			18: "crm",
			152: "workflow",
			135: "project",
			workplan: "workplan",
			blogTemplate: "blogTemplate"
		}
		const browserType = {
			37: "docids",
			prjtsk: "relatedprj",
			18: "relatedcus",
			152: "relatedwf",
			135: "projectids",//项目
			Upload: "relateddoc",//附件
		}
		list.map(item => {
			if (name === 'Browser') {
				let urlstr=this.openProjectAppLink(mirror[type],item.id,sortid);
				str +=`&nbsp;<a  href='${urlstr}' target='new'  linkid='${item.id}' linkType='${mirror[type]}'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;`
				idsArr.push(item.id)
			}
			if (name === 'Upload' && type === 'image') {
				str += '&nbsp;<img class="formImgPlay" src="' + item.imgSrc + '" onclick="ecCom.WeaRichText.playImg(this)" data-imgsrc="' + item.imgSrc + '" />&nbsp;'
			}
			if (name === 'Upload' && type === 'file') {
				str += `&nbsp;<a onclick='openProjectDiscussDoc(this,${ids[0]},${sortid},${acc_auth_url})' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.filename}</a>&nbsp;`
				if (item.showLoad) {
					let urlstr=item.loadlink+"&sortid="+sortid+acc_auth_url;
					str += `<a href='${urlstr}' target='_blank'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${getLabel(258,"下载")}(${item.filesize})</a>&nbsp;`
				}
			}
		})

		let oldBrowserList = { ...BrowserList };
		if (oldBrowserList[id] == undefined) {
			oldBrowserList[id] = {};
		}
		if (name != 'Upload') {
			oldBrowserList[id][browserType[type]] = list;
		} else {
			oldBrowserList[id]['relateddoc'].push({ id: ids[0] })

		}
		setBrowserList(oldBrowserList);
		return str
	}

	openProjectAppLink=(linkType, linkid, prjid)=>{
		const {exchangeList} = this.props.contentStore;
		let _exchangeList = toJS(exchangeList);
		let wf_auth_url = _exchangeList ? _exchangeList.wf_auth_url : "";
		let doc_auth_url = _exchangeList ? _exchangeList.doc_auth_url : "";
		let acc_auth_url = _exchangeList ? _exchangeList.acc_auth_url : "";
        if (linkType == "doc")
            return `/spa/document/index.jsp?id=${linkid}&prjid=${prjid}`+doc_auth_url;
        else if (linkType == "task")
            return `/spa/prj/index.html#/main/prj/taskCard?taskid=${linkid}`;
        else if (linkType == "crm")
            return `/spa/crm/static/index.html#/main/crm/customerView?customerId=${linkid}`;
        else if (linkType == "workflow")
            return `/spa/workflow/static4form/index.html#/main/workflow/req?fromModul=prj&modulResourceId=${prjid}&requestid=${linkid}`+wf_auth_url;
        else if (linkType == "project")
            return `/spa/prj/index.html#/main/prj/projectCard?prjid=${prjid}`;
        else
            return '';
	}
	
}

export default TabDiscuss


